<?php

namespace app\admin\controller\deerhome;

use app\common\controller\Backend;
use think\Db;
use Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
/**
 * 订单管理
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{

    /**
     * Order模型对象
     * @var \app\admin\model\deerhome\Order
     */
    protected $model = null;

    protected $searchFields = 'sn,user_phone';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\deerhome\Order;
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    public function index()
    {
        if (!$this->request->isAjax())
        {
            return $this->view->fetch();
        }
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $total = $this->model
                ->where($where)
                ->where("order_type",1)
                ->count();
        $list = $this->model
                ->where($where)
                ->where("order_type",1)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
        $result = array("total" => $total, "rows" => $list);

        return json($result);
    }


    public function detail()
    {
        $sn=$this->request->get("sn");
        $row = $this->model->get(['sn'=>$sn]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $mapKey=configDeer("qq_map_key");
        $row['user_phone']=\Tools\Config::tel($row['user_phone']);
        $row['imgs']=explode(",",$row['imgs']);
        $row['imgs']=array_filter($row['imgs']);
        $row['worker_imgs']=explode(",",$row['worker_imgs']);
        $row['worker_imgs']=array_filter($row['worker_imgs']);
        $row['status_txt']=$this->model->getStatusTextAttr($row['status']);
        $row['pay_log']=Db::name("deerhome_order_pay_log")->where("order_sn",$row['sn'])->order("id desc")->select();
        if (!$this->request->isAjax())
        {
            $this->view->assign('row', $row);
            $this->view->assign('mapKey', $mapKey);
            return $this->view->fetch();
        }
    }
    public function log($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if (!$this->request->isAjax())
        {
            $logs = Db::name("deerhome_order_log")->where("order_id",$row['id'])->order("id desc")->select();
            $this->view->assign('logs', $logs);
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
    }
    public function paidan($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if (!$this->request->isAjax())
        {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        if(!in_array($row['status'],[2,3])){
            $this->error('该订单状态不可派单');
        }
        if(!in_array($params['status'],[1,2])){
            $this->error('不支持的操作方式');
        }
        $time=substr($row['date_time'],0,5);
        //排除休假的服务人员
        $workerOffArr=Db::name("deerhome_worker_day")->where("day",$row['date_day'])->where("pb_rq","like","%{$time}%")->column("jz_worker_id");
        $workerOffArr=array_unique($workerOffArr);
        
        //系统派单，找出一个上班的服务人员
        if($params['status']==1){
            //剔除之前派过单的服务人员
            array_push($workerOffArr,$row['worker_id']);
            $worker=Db::name("deerhome_worker")->where("status",1)->where("is_working",1)->whereNotIn("id",$workerOffArr)->orderRaw("rand()")->find();
            if(!$worker){
                $this->error("预约的时间没有当班的服务人员");
            }
        }else{
            $worker=Db::name("deerhome_worker")->where("status",1)->where("id",$params['worker_id'])->find();
            if(!$worker){
                $this->error("该服务人员不存在或已停用");
            }
            if($worker['is_working']!=1){
                $this->error("该服务人员不在上班状态");
            }
            if(in_array($worker['id'],$workerOffArr)){
                $this->error("该服务人员在预约的时间没有当班");
            }
        }
        $arr=[];
        $arr['status']=3;
        $arr['worker_id']=$worker['id'];
        $arr['worker_get_time']=\date("Y-m-d H:i:s");
        $arr['worker_name']=$worker['uname'];

        //计算分成
        $items=Db::name("deerhome_items")->field("price,worker_fc_bl")->where("id",$row['jz_items_id'])->find();
        if(!$items){
            $this->error("服务项目已被删除");
        }
        $worker_price_base=\bcmul($row['price_need_pay'],$items['worker_fc_bl']/100,2);
        $arr['worker_price']=$worker_price_base;
        $arr['worker_price_note']="按交易额的{$items['worker_fc_bl']}%分成";
        
        //判断是否有额外分成
        $fc=Db::name("deerhome_worker_lev")->where("fybl",">",0)->where("id",$worker['jz_worker_lev_id'])->find();
        if($fc){
            $award=\bcmul($row['price_pre_fc'],$fc['fybl']/100,2);
            $arr['worker_price']=\bcadd($arr['worker_price'],$award,2);
            $arr['worker_price_note']="基本分成(按交易额{$items['worker_fc_bl']}%)￥{$worker_price_base}元，等级{$fc['name']}，额外奖励({$fc['fybl']}%)￥{$award}元";
        }
        $admin=$this->auth->getUserInfo();
        Db::startTrans();
        try{
            Db::name("deerhome_order")->where("id",$row['id'])->update($arr);
            Db::name("deerhome_order_log")->insert([
                'order_id'=>$row['id'],
                'add_time'=>date("Y-m-d H:i:s"),
                'ac_user'=>'管理员:'.$admin['username'],
                'note'=>"已".($params['status']==1?'安排':'指定')."{$worker['uname']}上门服务"
            ]);
            //如果之前有服务人员，则通知取消
            if($row['worker_id']>0){
                \Tools\Msg::toWorkerCancelOrder($row['worker_id'],$row['sn']);
            }
            //通知用户
            \Tools\Msg::toUserPaidan($row['jz_user_id'],$row['sn']);
            //通知服务人员
            \Tools\Msg::toWorkerNewOrder($worker['id'],$row['sn']);
            
            Db::commit();
        }catch(\Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success();
    }


}
